<?php

include 'header.php';
$page = 'import';

//check user login
if (!$user->user_exists) {
    header('Location: ./login.php');
    exit();
}

mb_language('Japanese');
mb_detect_order('auto');
mb_internal_encoding("Shift_JIS");

$csv = array();
// check there are no errors
if (!empty($_POST) && $_POST['submit'] && $_FILES['csv']['error'] == 0) {
    $name = $_FILES['csv']['name'];
    $ext = strtolower(end(explode('.', $_FILES['csv']['name'])));
    $type = $_FILES['csv']['type'];
    $tmpName = $_FILES['csv']['tmp_name'];
    setlocale(LC_ALL, 'ja_JP.EUCJP');
    // check the file is a csv
    if ($ext === 'csv') {

        header('Content-Type: text/html; charset=Shift_JIS');
        $content = file_get_contents($tmpName);

        $content = mb_convert_encoding($content, 'UTF-8', 'SJIS');
        $content = explode(PHP_EOL, $content);

        foreach ($content as $key => $value) {
            $value = explode(',', $value);
            $csv[(int) $key]['contract_code'] = isset($value[0]) ? $value[0] : "";
            $csv[(int) $key]['house_name'] = isset($value[1]) ? $value[1] : "";
            $csv[(int) $key]['house_address'] = isset($value[6]) ? $value[6] : "";
            $csv[(int) $key]['house_address_2'] = isset($value[7]) ? $value[7] : "";
            $csv[(int) $key]['room_number'] = isset($value[2]) ? $value[2] : "";
            $csv[(int) $key]['client_name'] = isset($value[3]) ? $value[3] : "";
            $csv[(int) $key]['client_phone'] = isset($value[4]) ? $value[4] : "";
            $csv[(int) $key]['guarantee_company_name'] = isset($value[5]) ? $value[5] : "";
        }
        /* if (($handle = fopen($tmpName, 'r')) !== FALSE) {
          // necessary if a large csv file
          set_time_limit(0);

          $row = 0;

          while (($data = fgetcsv($handle, 0, ',')) !== FALSE) {
          // number of fields in the csv
          $num = count($data);
          foreach ($data as $key => $value) {

          $value = mb_convert_encoding($value, 'UTF-8', "SJIS");
          $csv[$row][] = $value;
          }
          $row ++;
          }

          fclose($handle);
          } */
    }

    if (count($csv) > 1) {
        unset($csv[0]);

        $import = new Import();
        $import->import($csv);
        header("Location: notify.php?content=Import Success!!!&url_return=import.php");
    }
}
include 'footer.php';
